//
//  NSString+HACShield.m
//  HACShield
//
//  Created by Chengjie on 2019/5/22.
//

#import "NSString+HACShield.h"
#import "NSObject+HACSwizzling.h"

@implementation NSString (HACShield)

/**
 2019-05-25 15:57:08.947003+0800 HACShield[96370:4519641] str2 ===> __NSCFConstantString (常量区)
 2019-05-25 15:57:08.947075+0800 HACShield[96370:4519641] str3 ===> NSTaggedPointerString (栈区)
 2019-05-25 15:57:08.947144+0800 HACShield[96370:4519641] str6 ===> __NSCFString （堆区）
 2019-05-25 16:16:06.853656+0800 HACShield[97349:4530651] str_a ===> NSPlaceholderString (alloc)
 */
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 初始化 initWithString: stringWithString:
        hac_swizzleInstanceMethod(hac_getClass(@"NSP", @"laceholderString"), @selector(initWithString:), @selector(hac_initWithString:));
        // 其他公用方法
        hac_swizzleInstanceMethod(hac_getClass(@"NSS", @"tring"), @selector(stringByAppendingString:), @selector(hac_stringByAppendingString:));
        hac_swizzleInstanceMethod(hac_getClass(@"NSS", @"tring"), @selector(substringFromIndex:), @selector(hac_substringFromIndex:));
        hac_swizzleInstanceMethod(hac_getClass(@"NSS", @"tring"), @selector(substringToIndex:), @selector(hac_substringToIndex:));
        hac_swizzleInstanceMethod(hac_getClass(@"NSS", @"tring"), @selector(substringWithRange:), @selector(hac_substringWithRange:));
    });
}

- (instancetype)hac_initWithString:(NSString *)aString {
    if (aString && [aString isKindOfClass:NSString.class]) {
        return [self hac_initWithString:aString];
    }
    return [self hac_initWithString:@""];
}

#pragma mark -其他公用方法

- (NSString *)hac_stringByAppendingString:(NSString *)aString {
    if (aString && [aString isKindOfClass:NSString.class]) {
        return [self hac_stringByAppendingString:aString];
    }
    return self;
}

- (NSString *)hac_substringFromIndex:(NSUInteger)from {
    if (from >= 0 && from <= self.length) {
        return [self hac_substringFromIndex:from];
    }
    return nil;
}

- (NSString *)hac_substringToIndex:(NSUInteger)to {
    if (to >=0 && to <= self.length) {
        return [self hac_substringToIndex:to];
    }
    return nil;
}

- (NSString *)hac_substringWithRange:(NSRange)range {
    NSUInteger location = range.location;
    NSUInteger length = range.length;
    if (location >= 0 && length >= 0 && location + length <= self.length) {
        return [self hac_substringWithRange:range];
    }
    return nil;
}

@end
